<?php

namespace app\models;

use app\components\BaseActiveRecord;
use Yii;
use yii\db\Exception;

/**
 * This is the model class for table "{{%user_platform}}".
 *
 * @property int $id
 * @property string $type
 * @property int $uid
 * @property string $open_id
 * @property string $union_id
 * @property string $user_info
 * @property int $create_time
 *
 * @property User $user
 */
class UserPlatform extends BaseActiveRecord {
    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user_platform}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['uid', 'create_time'], 'integer'],
            [['type'], 'string', 'max' => 20],
            [['open_id', 'union_id'], 'string', 'max' => 160],
            [['user_info'], 'string', 'max' => 500],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => Yii::t('app', 'ID'),
            'type' => Yii::t('app', 'Type'),
            'uid' => Yii::t('app', 'Uid'),
            'open_id' => Yii::t('app', 'Open ID'),
            'union_id' => Yii::t('app', 'Union ID'),
            'user_info' => Yii::t('app', 'User Info'),
            'create_time' => Yii::t('app', 'Create Time'),
        ];
    }

    public function getUser() {
        return $this->hasOne(User::class, ['id' => 'uid']);
    }

    /**
     * @param $data
     * @param $type
     * @return array|bool
     * @throws Exception
     */
    public function savePlatform($data, $type) {
        $open_id = isset($data['openid']) ? $data['openid'] : $data['uid'];
        $union_id = isset($data['union_id']) ? $data['union_id'] : '';

        $model = static::findOne(['open_id' => $open_id, 'type' => $type]);
        if ($model) {
            if ($model->user) {
                $model->user->loginCookie();
                return static::retOK();
            }
        }
        $_user_data = $this->getPlatformData($type, $data);
        if (!$_user_data) {
            throw new Exception(Yii::t('app', '{type}: not found.', $type));
        }
        return $this->saveUserPlatform($_user_data, $type, $open_id, $union_id, $model);
    }

    public function getPlatformData($type, $info) {
        $map = [
            'qq' => ['nickname' => 'nickname', 'avatar' => 'figureurl_1'],
            'wx' => ['nickname' => 'nickname', 'avatar' => 'headimgurl'],
            'weibo' => ['nickname' => 'screen_name', 'avatar' => 'avatar_large'],
            'google' => [
                'nickname' => 'screen_name', 'avatar' => 'avatar_large',
            ]
        ];
        if (!isset($map[$type])) {
            return NULL;
        }
        $fields = $map[$type];
        $data = [];
        foreach ($fields as $field => $_field) {
            $data[$field] = $info[$_field];
        }
        return $data;
    }

    /**
     * @param $userData
     * @param $type
     * @param $open_id
     * @param string $union_id
     * @param $model
     * @return array|bool
     * @throws Exception
     */
    protected function saveUserPlatform($userData, $type, $open_id, $union_id, $model) {
        $user = new UserAr();
        $user->setAttributes($userData);
        $user->save(FALSE);

        if (!$model) {
            $model = new UserPlatform();
            $model->uid = $user->id;
            $model->type = $type;
            $model->open_id = $open_id;
            $model->union_id = $union_id;
            $model->save();
        }

        $user->loginCookie();

        return self::retOK();
    }
}
